<?php
namespace Admin\Controller;
use Think\Controller;
// use Admin\Common\CommonController;
class LoginController extends Controller {
    public function index(){
    	if ($_POST) {
    		$username=I('post.username');
    		$password=I('post.password');
    		$code=I('post.code');

            $link=M('user');
            $sql="select * from user where username='{$username}'";
            $res=$link->query($sql);
            $data=current($res);//减为一维数组
    		// var_dump($code);exit;
    		if ($username!=$data['username']) {
    			$this->error('用户名或密码错误');
    		}elseif (md5($password)!=$data['password']) {
    			$this->error('用户名或密码错误');
    		}elseif (!$this->check_verify($code)) {
    			// var_dump($this->check_verify($code));exit;
    			$this->error('验证码错误!');
    		}else{
    			$this->success('登陆成功!',U('admin/home/index'),2);
                $_SESSION['username']=$data['username'];
                $_SESSION['id']=$data['id'];

    		}
    	}else{
    		$this->display('login');
    	}
    	
    }

    public function code(){
    	$config =    array(
    		'imageW'      =>    180,
    		'imageH'      =>    45,
	        'fontSize'    =>    22,    // 验证码字体大小
	        'length'      =>    4,     // 验证码位数
	        'useNoise'    =>    false, // 关闭验证码杂点
	    );
	    $Verify =     new \Think\Verify($config);//实例化验证码
	    $Verify->useImgBg = true;//验证码背景图片
	    $Verify->entry();
    }

    function check_verify($code, $id = ''){
	    $verify = new \Think\Verify();
	    return $verify->check($code, $id);
	}

    public function loginout(){
        session_unset();
        session_destroy();
        $this->success('退出成功!',U('admin/login/index'),2);
    }

}
